import { createRequest } from "./create";
// import { RequestErrorCode } from "./constant";
import { showToast } from "vant";
import { useAuthStore } from "@/store/modules/auth";

export const request = createRequest(
  { baseURL: import.meta.env.VITE_SERVICE_BASE_URL, timeout: 60000 },
  {
    onRequest: config => {
      const { headers } = config;
      const authStore = useAuthStore();
      headers["Authorization"] = "Bearer " + authStore.token;
      return config;
    },
    isSuccess: response => {
      const successCode =
        import.meta.env.VITE_SERVICE_SUCCESS_CODE?.split(",") || [];
      return successCode.includes(String(response.data.code));
    },
    transformResponse: response => {
      return response.data.data;
    },
    onFail: async response => {
      const { code } = response.data;
      const expiredCode =
        import.meta.env.VITE_SERVICE_EXPIRED_TOKEN_CODE?.split(",") || [];

      if (expiredCode.includes(code)) {
        // 退出登录
        return null;
      }

      return null;
    },
    onError: error => {
      let { message } = error;
      let errorCode = "";
      const data = error.response?.data;
      // if (error.code === RequestErrorCode) {
      message = data?.message || message;
      errorCode = String(data?.code || "");
      // }

      // 根据code做一些业务的特殊判断
      const expiredCode =
        import.meta.env.VITE_SERVICE_EXPIRED_TOKEN_CODE?.split(",") || [];
      if (expiredCode.includes(errorCode)) {
        return;
      }

      showToast(message);
    }
  }
);
